# encoding: utf-8
import uuid
import hashlib
import json
from datetime import datetime, timedelta
import platform


def get_hardware_id():
    """获取设备硬件指纹（包含MAC、CPU、主板信息）"""
    # 获取MAC地址
    mac = uuid.getnode()

    # 初始化硬件信息
    cpu_info = "UNKNOWN_CPU"
    board_info = "UNKNOWN_BOARD"

    # Windows系统
    if platform.system() == "Windows":
        try:
            import wmi
            c = wmi.WMI()
            # 获取CPU信息
            cpu_info = c.Win32_Processor()[0].ProcessorId
            # 获取主板信息
            board_info = c.Win32_BaseBoard()[0].SerialNumber
        except:
            pass

    # Linux系统
    elif platform.system() == "Linux":
        try:
            # 获取CPU信息
            with open('/proc/cpuinfo', 'r') as f:
                for line in f:
                    if line.strip() and 'serial' in line.lower():
                        cpu_info = line.split(':')[1].strip()
                        break
            # 获取主板信息
            with open('/sys/class/dmi/id/board_serial', 'r') as f:
                board_info = f.read().strip()
        except:
            pass

    # Mac系统
    elif platform.system() == "Darwin":
        try:
            import subprocess
            # 获取CPU信息
            cpu_info = subprocess.check_output(
                "sysctl -n machdep.cpu.brand_string",
                shell=True
            ).decode().strip()
            # 获取主板信息
            board_info = subprocess.check_output(
                "ioreg -l | grep IOPlatformSerialNumber",
                shell=True
            ).decode().split('=')[-1].strip().strip('"')
        except:
            pass

    # 组合硬件信息
    hardware_str = f"{mac}-{cpu_info}-{board_info}"
    return hashlib.sha256(hardware_str.encode()).hexdigest()


def generate_license(hardware_id, days=365, output_file="license.lic"):
    """
    生成授权文件
    :param hardware_id: 硬件指纹
    :param days: 授权天数
    :param output_file: 授权文件输出路径
    """
    expire_date = (datetime.now() + timedelta(days=days)).strftime("%Y-%m-%d")
    license_data = {
        "hardware_id": hardware_id,
        "expire_date": expire_date,
        "signature": hashlib.sha256(
            f"{hardware_id}{expire_date}YOUR_SECRET_KEY_{platform.node()}".encode()
        ).hexdigest()  # 更复杂的签名密钥
    }

    with open(output_file, "w") as f:
        json.dump(license_data, f)

    print(f"授权文件已生成: {output_file}")
    print(f"硬件指纹: {hardware_id}")
    print(f"到期日期: {expire_date}")


def validate_license(license_file="license.lic"):
    """
    验证授权文件
    :param license_file: 授权文件路径
    :return: (bool, str) 验证结果和消息
    """
    try:
        with open(license_file, "r") as f:
            license_data = json.load(f)
    except FileNotFoundError:
        return False, "授权文件不存在"
    except json.JSONDecodeError:
        return False, "授权文件格式错误"

    # 验证硬件ID
    current_hardware = get_hardware_id()
    if license_data["hardware_id"] != current_hardware:
        return False, "硬件不匹配（可能更换了主板或CPU）"

    # 验证签名
    expected_signature = hashlib.sha256(
        f"{license_data['hardware_id']}{license_data['expire_date']}YOUR_SECRET_KEY_{platform.node()}".encode()
    ).hexdigest()

    if license_data["signature"] != expected_signature:
        return False, "授权签名无效"

    # 验证有效期
    expire_date = datetime.strptime(license_data["expire_date"], "%Y-%m-%d")
    if datetime.now() > expire_date:
        return False, "授权已过期"

    return True, "授权验证通过"


def show_hardware_info():
    """显示当前硬件信息（用于调试）"""
    mac = uuid.getnode()
    print(f"MAC地址: {mac}")
    print(f"系统类型: {platform.system()}")
    print(f"计算机名称: {platform.node()}")
    print(f"硬件指纹: {get_hardware_id()}")


# 使用示例
if __name__ == "__main__":
    show_hardware_info()
    # import argparse


    # parser = argparse.ArgumentParser(description="软件授权管理系统")
    # parser.add_argument("--generate", action="store_true", help="生成新的授权文件")
    # parser.add_argument("--validate", action="store_true", help="验证授权文件")
    # parser.add_argument("--days", type=int, default=365, help="授权天数（默认365天）")
    # parser.add_argument("--info", action="store_true", help="显示硬件信息")

    # args = parser.parse_args()

    # if args.info:
    #     show_hardware_info()
    # elif args.generate:
    #     hardware_id = get_hardware_id()
    #     generate_license(hardware_id, days=args.days)
    # elif args.validate:
    #     result, message = validate_license()
    #     print(message)
    # else:
    #     print("请指定操作参数，使用--help查看帮助")